package com.zerotwo.exam.center.utils;

import com.zerotwo.exam.center.enums.QuestionClassificationTypeEnum;
import com.zerotwo.exam.center.enums.QuestionTypeEnum;
import com.zerotwo.exam.center.enums.QuestionVisibleEnum;
import com.zerotwo.exam.center.model.Question;
import com.zerotwo.exam.center.model.Questions;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.jsoup.Jsoup;

@Service
@Slf4j
public class ImportExcel {
    private static final Logger logger = LoggerFactory.getLogger(ImportExcel.class);

    public List<Question> importExcel(MultipartFile file) throws IOException {
        List<Question> questionsList = new ArrayList<>();
        try (InputStream inputStream = file.getInputStream();
             HSSFWorkbook workbook = new HSSFWorkbook(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0);
            for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                if (row != null) {
                    try {
                        Question questions = createQuestionFromRow(row);
                        questionsList.add(questions);
                    } catch (IllegalArgumentException e) {
                        logger.error("Error processing row {}: {}", rowIndex, e.getMessage());
                    }
                }
            }
        }
        return questionsList;
    }

    private Question createQuestionFromRow(Row row) {
        Question questions = new Question();

        // 获取单元格并检查类型
        Cell idCell = row.getCell(0);
        if (idCell != null && idCell.getCellType() == CellType.NUMERIC) {
            questions.setId((int) idCell.getNumericCellValue());
        }

        Cell contentCell = row.getCell(1);
        if (contentCell != null && contentCell.getCellType() == CellType.STRING) {
            questions.setContent(cleanHtmlTags(contentCell.getStringCellValue()));
        }

        Cell typeCell = row.getCell(2);
        if (typeCell != null && typeCell.getCellType() == CellType.STRING) {
            String typeLabel = cleanHtmlTags(typeCell.getStringCellValue());
            System.out.println("Type Label: " + typeLabel); // 添加调试输出
            questions.setType(getQuestionTypeByLabel(Integer.valueOf(typeLabel)));
        }

        Cell analysisCell = row.getCell(3);
        if (analysisCell != null && analysisCell.getCellType() == CellType.STRING) {
            questions.setAnalysis(cleanHtmlTags(analysisCell.getStringCellValue()));
        }

        Cell difficultyCell = row.getCell(4);
        if (difficultyCell != null && difficultyCell.getCellType() == CellType.NUMERIC) {
            questions.setDifficulty((int) difficultyCell.getNumericCellValue());
        }

        Cell scoreCell = row.getCell(5);
        if (scoreCell != null && scoreCell.getCellType() == CellType.NUMERIC) {
            questions.setScore((float) scoreCell.getNumericCellValue());
        }

        Cell isPublicCell = row.getCell(6);
        if (isPublicCell != null && isPublicCell.getCellType() == CellType.NUMERIC) {
            Integer isPublicValue = (int) isPublicCell.getNumericCellValue();
            questions.setIsPublic(getQuestionVisibleEnum(isPublicValue));
        }

        Cell courseIdCell = row.getCell(7);
        if (courseIdCell != null && courseIdCell.getCellType() == CellType.NUMERIC) {
            questions.setCourseId((int) courseIdCell.getNumericCellValue());
        }

        Cell tagIdCell = row.getCell(8);
        if (tagIdCell != null && tagIdCell.getCellType() == CellType.NUMERIC) {
            questions.setTagId((int) tagIdCell.getNumericCellValue());
        }

        Cell teacherIdCell = row.getCell(9);
        if (teacherIdCell != null && teacherIdCell.getCellType() == CellType.NUMERIC) {
            questions.setTeacherId((int) teacherIdCell.getNumericCellValue());
        }

        Cell contentsCell = row.getCell(10);
        if (contentsCell != null && contentsCell.getCellType() == CellType.STRING) {
            questions.setContents(cleanHtmlTags(contentsCell.getStringCellValue()));
        }

        Cell questionIdCell = row.getCell(11);
        if (questionIdCell != null && questionIdCell.getCellType() == CellType.NUMERIC) {
            questions.setQuestionId((int) questionIdCell.getNumericCellValue());
        }

        Cell answerCell = row.getCell(12);
        if (answerCell != null && answerCell.getCellType() == CellType.STRING) {
            questions.setAnswer(cleanHtmlTags(answerCell.getStringCellValue()));
        }



        return questions;
    }

    private String cleanHtmlTags(String htmlContent) {
        return Jsoup.parse(htmlContent).text();
    }

//    private QuestionTypeEnum getQuestionTypeByLabel(Object label) {
//        if (label instanceof Integer) {
//            int intLabel = (Integer) label;
//            for (QuestionTypeEnum type : QuestionTypeEnum.values()) {
//                if (type.getValue() == intLabel) {
//                    return type;
//                }
//            }
//            System.out.println("Available values: " + Arrays.stream(QuestionTypeEnum.values()).map(QuestionTypeEnum::getValue).toList());
//        }
//        throw new IllegalArgumentException("Invalid question type at column 2: " + label + ". Available types: " + Arrays.stream(QuestionTypeEnum.values()).map(QuestionTypeEnum::getValue).toList());
//    }
private static QuestionTypeEnum getQuestionTypeByLabel(Integer value) {
    for (QuestionTypeEnum type : QuestionTypeEnum.values()) {
        if (type.getValue().equals(value)) {
            return type;
        }
    }
    throw new IllegalArgumentException("Invalid visibility value: " + value + ". Available values: " + Arrays.stream(QuestionVisibleEnum.values()).map(QuestionVisibleEnum::getValue).toList());
}
    private QuestionVisibleEnum getQuestionVisibleEnum(Integer value) {
        for (QuestionVisibleEnum isPublic : QuestionVisibleEnum.values()) {
            if (isPublic.getValue().equals(value)) {
                return isPublic;
            }
        }
        throw new IllegalArgumentException("Invalid visibility value: " + value + ". Available values: " + Arrays.stream(QuestionVisibleEnum.values()).map(QuestionVisibleEnum::getValue).toList());
    }
}
